# coding: utf-8
'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2021-05-12 10:20:46
LastEditors: peng2.zhang
LastEditTime: 2022-03-17 11:21:50
'''
import time
import ujson
from datetime import datetime, date
from ci_conclude.models.db import DBConnection
from ci_conclude.models.models import JenkinsBuildHistory
from ci_conclude.services.base import BaseService
from ci_conclude.utils.error_code import ERROR
from ci_conclude.utils.validations import Validator, validate
from voluptuous import Schema, ALLOW_EXTRA, Required, All, Any, Coerce, Length
from ci_conclude.log import logger
from ci_conclude.const import ADMAPCI_JOBS
# from celery_app import task_deploy
# from celery_app.base import DBConnection


class JenkinsBuildHistoryService(BaseService,Validator):

    def create_kwargs(self, **kwargs):
        filtered_kwargs = JenkinsBuildHistory.filter_kwargs(kwargs)
        build_history = JenkinsBuildHistory(**filtered_kwargs)
        self.db.add(build_history)
        self.db.flush()
        self.db.commit()

    @classmethod
    def create(cls, **kwargs):
        with DBConnection() as db_conn:
            svc = cls(db_conn)
            res = svc.create_kwargs(**kwargs)

    def get_admapci_white_list(self):
        admapci_jobs = ADMAPCI_JOBS.to_list()
        admapci_jobs = [i["ID"] for i in admapci_jobs]
        return admapci_jobs
    
    def get_sql(self, start_time=None):
        """
            start_time格式: %Y-%m-%d或者%Y-%m-%d %H:%M:%S
        """
        sql = f"""select
                    t1.id, t1.job_name, t1.build_id, t1.build_version, t1.git_commit_branch, t1.git_commit_id, t1.git_commit_by, t1.git_commit_time, t1.job_status, t1.job_duration, t1.create_time as finish_time, t1.allure_pass_rate, t1.allure_total, t1.allure_failed, t1.junit_tests, t1.junit_failures, t1.sonar_bugs, t1.sonar_code_smell, t1.sonar_vulnerability
                from
                    jenkins_build_history t1
                inner join(
                    select
                        max(id) as id, job_name
                    from
                        jenkins_build_history t1 group by job_name) t2
                on 
                    t2.job_name = t1.job_name and t2.id = t1.id
                where t2.job_name like 'admapci_%'"""
        if start_time:
            sql += f""" and t1.create_time >= '{start_time}'"""
        return sql

    def as_dict(self, data):
        d = dict(data)
        for k,v in d.items():
            if isinstance(v, date):
                d[k] = v.strftime("%Y-%m-%d")
                # logger.info(f"date {k}: {d[k]}")
            if isinstance(v, datetime):
                d[k] = v.strftime("%Y-%m-%d %H:%M:%S")
                # logger.info(f"datetime {k}: {d[k]}")
        return d
    
    def get_current_date_build_list(self, start_time=None):
        if not start_time:
            now_date = datetime.now().strftime("%Y-%m-%d")
            print(now_date)
        else:
            now_date = start_time
        # sql = f"""select
        #             t1.id, t1.job_name, t1.build_id, t1.build_version, t1.git_commit_branch, t1.git_commit_id, t1.git_commit_by, t1.git_commit_time, t1.job_status, t1.job_duration, t1.create_time as finish_time, t1.allure_pass_rate, t1.allure_total, t1.allure_failed, t1.junit_tests, t1.junit_failures
        #         from
        #             jenkins_build_history t1
        #         inner join(
        #             select
        #                 max(id) as id, job_name, build_id, build_version, git_commit_branch, git_commit_id, git_commit_by, sonar_bugs, create_time
        #             from
        #                 jenkins_build_history t1 group by job_name) t2
        #         on 
        #             t2.job_name = t1.job_name and t2.id = t1.id
        #         where t2.job_name like 'admapci_%' and t1.create_time >= '{now_date}'"""
        sql = self.get_sql(now_date)
        build_list = self.db.execute(sql).fetchall()
        #b_list = [dict(x) for x in build_list]
        b_list = [self.as_dict(x) for x in build_list]
        return b_list

    def get_latest_build_list(self):
        sql = self.get_sql()
        build_list = self.db.execute(sql).fetchall()
        #b_list = [dict(x) for x in build_list]
        b_list = [self.as_dict(x) for x in build_list]
        return b_list
